import { Request, Response } from "express";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import pool from "../db";
import { getClientIp } from "../utils/ipHelper"; // 获取 IP 地址的工具函数

export class AuthController {
    /**
     * 用户注册
     */
    static async register(req: Request, res: Response) {
        const { username, password, email, phone } = req.body;

        if (!username || !password) {
            return res.status(400).json({ error: "用户名和密码不能为空!" });
        }

        try {
            // 检查用户名是否已被注册
            const [userRows] = await pool.query("SELECT id FROM user_account WHERE username = ?", [username]);
            if ((userRows as any[]).length > 0) {
                return res.status(400).json({ error: "用户名已被注册" });
            }

            // // 检查邮箱是否已被使用
            // if (email) {
            //     const [emailRows] = await pool.query("SELECT id FROM user_account WHERE email = ?", [email]);
            //     if ((emailRows as any[]).length > 0) {
            //         return res.status(400).json({ error: "该邮箱已被注册" });
            //     }
            // }

            // // 检查手机号是否已被使用
            // if (phone) {
            //     const [phoneRows] = await pool.query("SELECT id FROM user_account WHERE phone = ?", [phone]);
            //     if ((phoneRows as any[]).length > 0) {
            //         return res.status(400).json({ error: "该手机号已被注册" });
            //     }
            // }

            // 哈希加密密码
            const hashedPassword = await bcrypt.hash(password, 10);
            const registerIp = getClientIp(req); // 获取注册 IP

            // 插入用户数据
            const [result] = await pool.query(
                "INSERT INTO user_account (username, password_hash, email, phone, register_ip) VALUES (?, ?, ?, ?, ?)",
                [username, hashedPassword, email, phone, registerIp]
            );

            return res.status(201).json({
                message: "注册成功",
                userId: (result as any).insertId, // 返回新注册用户的 ID
            });
        } catch (error) {
            console.error(error);
            return res.status(500).json({ error: "服务器错误" });
        }
    }

    /**
     * 用户登录
     */
    static async login(req: Request, res: Response) {
        let { username,email, password } = req.body;
        if(!username && email){
            username = email;
        }

        if (!username|| !password) {
            return res.status(400).json({ error: "用户名和密码不能为空!" });
        }

        try {
            // 查询用户
            const [rows] = await pool.query("SELECT id, password_hash FROM user_account WHERE username = ?", [username]);
            if ((rows as any[]).length === 0) {
                return res.status(401).json({ error: "用户名或密码错误" });
            }

            const user = (rows as any[])[0];

            // 验证密码
            const isMatch = await bcrypt.compare(password, user.password_hash);
            if (!isMatch) {
                return res.status(401).json({ error: "用户名或密码错误" });
            }

            // 生成 JWT 令牌
            const token = jwt.sign(
                { id: user.id, username },
                process.env.JWT_SECRET!,
                { expiresIn: "24h" }
            );

            // 记录登录 IP 和时间
            const loginIp = getClientIp(req);
            await pool.query(
                "UPDATE user_account SET last_login_ip = ?, last_login_time = NOW() WHERE id = ?",
                [loginIp, user.id]
            );

            return res.status(200).json({
                message: "登录成功",
                token,
                userId: user.id,
            });
        } catch (error) {
            console.error(error);
            return res.status(500).json({ error: "服务器错误" });
        }
    }
}
